import sys 
sys.path.append("./gen-py/parse")
 
from Parse import *
from ttypes import *
from thrift.Thrift import TType, TMessageType, TException
from thrift.Thrift import TProcessor
from thrift.transport import TSocket
from thrift.protocol import TBinaryProtocol, TProtocol
from thrift.server import TServer,TNonblockingServer
import logging
from constants import *

import face_recognition
import cv2
logging.basicConfig(filename='logger.log', level=logging.INFO, format='%(asctime)s  %(filename)s : %(levelname)s  %(message)s', datefmt='%Y-%m-%d %H:%M:%S')

names = [
	"catherine",
	"william",
	]
	
images = []	

face_encodings = []

class ParseHandler:
 
    def parseHtml2Xml(self, html):
        logging.info("start parse html")
        unknown_image          = face_recognition.load_image_file("unknown.jpg")
        unknown_face_encodings = face_recognition.face_encodings(unknown_image)
        face_locations         = face_recognition.face_locations(unknown_image)
        for i in range(len(unknown_face_encodings)):
            unknown_encoding         = unknown_face_encodings[i]
            face_location            = face_locations[i]
            top, right, bottom, left = face_location
            cv2.rectangle(unknown_image, (left, top), (right, bottom), (0, 255, 0), 2)
			
            results = face_recognition.compare_faces(face_encodings, unknown_encoding)
            for j in range(len(results)):
                if results[j]:
                    name = names[j]
                    cv2.putText(unknown_image, name, (left-10, top-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
                    unknown_image_rgb = cv2.cvtColor(unknown_image, cv2.COLOR_BGR2RGB)
                    #cv2.imshow("Output", unknown_image_rgb)
                    #cv2.waitKey(0)
        return "1234"
		
		
def run():
    handler = ParseHandler()
    processor = Processor(handler)
 
    transport = TSocket.TServerSocket('localhost', 9234)
 
    tfactory = TTransport.TBufferedTransportFactory()
 
    pfactory = TBinaryProtocol.TBinaryProtocolFactory()

    server = TNonblockingServer.TNonblockingServer(processor, transport, inputProtocolFactory=pfactory) 

    #server = TServer.TThreadPoolServer(processor, transport, tfactory, pfactory)
    #server.setNumThreads(5)

    for name in names:
        filename = name + ".jpg"
        image = face_recognition.load_image_file(filename)
        images.append(image)


    for image in images:
        encoding = face_recognition.face_encodings(image)[0]
        face_encodings.append(encoding)
	
    logging.info('start thrift serve in python')
    server.serve()
    logging.info('done!')
 
if __name__ == '__main__':
    run()

